import Vue from 'vue'
import VueRouter from 'vue-router'
//非懒加载路由
import Home from '@/components/Home.vue'
//路由懒加载
const About = () => import('@/components/About.vue')
const User = () => import('@/components/User.vue')
const Pass = () => import('@/components/Pass.vue')
const Login = () => import('@/components/Login.vue')
const Order = () => import('@/components/Order.vue')
const News = () => import('@/components/News.vue')
const NewsDetail = () => import('@/components/NewsDetail.vue')
const List = () => import('@/components/List.vue')
//重新定义router的push函数，解决路由不能重复点击的问题
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home', meta: { needLogin: true } },
  { path: '/home', component: Home, name: 'Home', meta: { needLogin: true } },
  //路由传参的写法，name是参数名称，实际的url = /home/tom
  { path: '/home/:name', component: Home, name: 'Home' },
  {
    path: '/news',
    component: News,
    //路由独享守卫
    beforeEnter(to, from, next) {
      let path = from.path
      if (path === '/about') {
        let str = sessionStorage.getItem('USER_LOGIN')
        console.log(str)
        if (str) {
          //已经登录了就放行
          return next()
        }
        next({ path: '/login', query: { login_msg: '请先登录' } })
      }
      next()
    }
  },
  { path: '/news/:id', component: NewsDetail },
  { path: '/about', component: About },
  {
    path: '/user',
    component: User,
    children: [
      { path: 'pass', component: Pass },
      { path: 'order', component: Order }
    ]
  },
  { path: '/login', component: Login, name: 'Login' },
  { path: '/list', component: List }
]
const router = new VueRouter({ routes })
//全局的路由前置守卫
// router.beforeEach(function(to, from, next) {
//   let needLogin = to.meta.needLogin || false
//   if (needLogin) {
//     //判断当前人员是否登录过，判断登录信息是否存在，
//     //在sessionStorage中的用户名是否有
//     let str = sessionStorage.getItem('USER_LOGIN')
//     console.log(str)
//     if (str) {
//       //已经登录了就放行
//       return next()
//     }
//     //需要登录，却没有登录，就跳转到登录页
//     //sessionStorage.setItem('LOGIN_MSG', '请先登录')
//     next({ path: '/login', query: { login_msg: '请先登录' } })
//   } else {
//     next()
//   }
// })

//全局路由的后置守卫
// router.afterEach((to, from) => {
//   console.log(to.path, from.path)
//   console.log('路由后置守卫')
// })
export default router
